// import 'package:flutter/material.dart';
// import 'package:image_picker/image_picker.dart';
// import 'dart:convert';
// import 'dart:io';
//
// class CameraOrGallery {
//   static var imgPath;
//   static String data = "";
//   static ImagePicker imagepicker = new ImagePicker();
//   /*拍照*/
//   static takePhoto() async {
//     imgPath = await imagepicker.pickImage(source: ImageSource.camera, maxHeight: 480, maxWidth: 640);
//     data = encodeBase64();
//   }
//
//   /*相册*/
//   static openGallery() async {
//     imgPath = await imagepicker.pickImage(source: ImageSource.gallery, maxHeight: 480, maxWidth: 640);
//     data = encodeBase64();
//   }
//
//   static String encodeBase64() {
//     File imageFile = File(imgPath!.path);
//     List<int> imageBytes = imageFile.readAsBytesSync();
//     String baseImg = base64Encode(imageBytes);
//     return baseImg;
//   }
//
// }



import 'dart:convert';
import 'package:dio/dio.dart';
import 'package:my_app/conponate/user_info.dart';
import 'package:my_app/tools/http_server.dart';
import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';
import 'dart:io';

class ImagePickerWidget extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return _ImagePickerState();
  }
}

class _ImagePickerState extends State<ImagePickerWidget> {
  ImagePicker imagepicker = new ImagePicker();
  var _imgPath;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          backgroundColor: Colors.blueGrey,
          title: Text("ImagePicker",style: TextStyle(fontSize: 20,),),
        ),
        body: SingleChildScrollView(
          child: Column(
            // mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              SizedBox(height: 200,),
              _ImageView(_imgPath),
              SizedBox(height: 30,),
              RaisedButton(
                onPressed: _takePhoto,
                color: Colors.blueGrey,

                child: Text("拍照",style: TextStyle(fontSize: 20,color: Colors.white),),
              ),
              SizedBox(height: 10,),
              RaisedButton(
                onPressed: _openGallery,
                color: Colors.blueGrey,
                child: Text("图库",style: TextStyle(fontSize: 20,color: Colors.white),),
              ),
            ],
          ),
        ));
  }

  /*图片控件*/
  Widget _ImageView(imgPath) {
    if (imgPath == null) {
      return Center(
        child: Text("请选择图片或拍照",style: TextStyle(fontSize: 20,color: Colors.blueGrey,fontWeight: FontWeight.bold),),
      );
    } else {
      return Image.file(
        imgPath,
      );
    }
  }


  /*拍照*/
  _takePhoto() async {
    var image = await imagepicker.pickImage(source: ImageSource.camera, maxWidth: 640, maxHeight: 480);

    setState(() {
      _imgPath = File(image!.path);
      HttpServer.uploadImage(image!.path);
      _toSearch();
    });

  }

  /*相册*/
  _openGallery() async {
    var image = await imagepicker.pickImage(source: ImageSource.gallery, maxWidth: 640, maxHeight: 480);

    setState(() {
      _imgPath = File(image!.path);
      HttpServer.uploadImage(image!.path);
      _toSearch();
    });

  }


  _toSearch(){
    Navigator.of(context).push(
        MaterialPageRoute(
            builder: (context) {
              return Scaffold(
                appBar: AppBar(
                  title: Text(
                    "图像搜索",
                  ),
                  centerTitle: true,
                  elevation: 5.0,
                ),
                body:  FutureBuilder(
                  future: HttpServer.postImg(),
                  builder: (BuildContext context, AsyncSnapshot<List> snapshot){
                    if(snapshot.connectionState == ConnectionState.done){
                      if(snapshot.hasError){
                        return Center(
                          child: Text("未查询到相关物品"),
                        );
                      }else{
                        var data = snapshot.data;
                        print("data: $data");
                        List<Map<String, dynamic>> tiles = (data as List).cast();
                        print("tiles: ${tiles.length}");
                        return ListView.builder(
                            itemCount: tiles.length,
                            shrinkWrap: true,
                            itemBuilder: (BuildContext context, int index) {
                              return ListTile(
                                title:  Text('${(tiles)[index]["name"]}'),
                                subtitle: Text('${(tiles)[index]["category"]}'),
                                trailing: Icon(Icons.star),
                                onTap: (){
                                  showDialog<Null>(
                                      context: context,
                                      barrierDismissible: false,
                                      builder: (BuildContext context) {
                                        HttpServer.star(UserInfo.userName, (tiles)[index]["name"], "收藏");
                                        return new AlertDialog(
                                          title: new Text('已收藏'),
                                          actions: <Widget>[
                                            new FlatButton(
                                              child: new Text('确定'),
                                              onPressed: () {
                                                Navigator.of(context).pop();
                                              },
                                            ),
                                          ],
                                        );
                                      }
                                  ).then((val) {
                                    print(val);
                                  });
                                },
                              );
                            }
                        );
                      }
                    } else{
                      return Align(
                        child: CircularProgressIndicator(),
                        alignment: Alignment.center,
                      );
                    }
                  },
                ),
              );
            }
        )
    );
  }
}




